package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@WebServlet("/FlightAdjustmentServlet")
@MultipartConfig
public class FlightAdjustmentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        String operation = request.getParameter("operation");
        if (operation == null) {
            response.getWriter().write("failure");
            return;
        }
        List<String> input = new ArrayList<>();
        input.add(operation); // 操作类型作为首位参数

        switch (operation) {
            case "addFlight": {
                input.add(request.getParameter("starttime"));
                input.add(request.getParameter("endtime"));
                input.add(request.getParameter("takeoffstation"));
                input.add(request.getParameter("arrivalstation"));
                input.add(request.getParameter("boardingtime"));
                break;
            }
            case "addAirline": {
                String fid = request.getParameter("fid");
                String position = request.getParameter("position");
                String remain = request.getParameter("remain");
                String date = java.time.LocalDate.now().toString();
                input.add(fid);       // 第1位：fid
                input.add(date);      // 第2位：date
                input.add(position);  // 第3位：position
                input.add(remain);    // 第4位：remain
                break;
            }
            case "deleteAirline": {
                String aid = request.getParameter("aid");
                input.add(aid);
                break;
            }
            case "deleteFlight": {
                String fid = request.getParameter("fid");
                input.add(fid);
                break;
            }
            case "modifyFlight": {
                String fid = request.getParameter("fid");
                String field = request.getParameter("field");
                String newValue = request.getParameter("newValue");

                // 查询原航班信息
                DB_Flight dbFlight = new DB_Flight();
                List<String> flightConditions = new ArrayList<>();
                flightConditions.add("fid=" + fid);
                List<String> originalFlight = dbFlight.find(flightConditions);
                if (originalFlight.isEmpty()) {
                    response.getWriter().write("failure");
                    return;
                }
                String[] flightData = originalFlight.get(0).split(",");

                // 构造更新参数（fid, starttime, endtime, takeoffstation, arrivalstation, boardingtime）
                List<String> updateFlightParams = new ArrayList<>();
                updateFlightParams.add(fid); // 最后一位是fid（WHERE条件）
                updateFlightParams.add(field.equals("starttime") ? newValue : flightData[1]); // starttime
                updateFlightParams.add(field.equals("endtime") ? newValue : flightData[2]);   // endtime
                updateFlightParams.add(field.equals("takeoffstation") ? newValue : flightData[3]); // takeoffstation
                updateFlightParams.add(field.equals("arrivalstation") ? newValue : flightData[4]); // arrivalstation
                updateFlightParams.add(field.equals("boardingtime") ? newValue : flightData[5]); // boardingtime
                input.addAll(updateFlightParams);
                break;
            }

            case "modifyAirline": {
                String aid = request.getParameter("aid"); // 从modifyForm中传递aid（需在前端补充隐藏域）
                String field = request.getParameter("field"); // 字段（position/remain）
                String newValue = request.getParameter("newValue");

                // 查询原席别数据
                DB_Airline dbAirline = new DB_Airline();
                List<String> airlineConditions = new ArrayList<>();
                airlineConditions.add("aid=" + aid);
                List<String> originalAirline = dbAirline.find(airlineConditions);
                if (originalAirline.isEmpty()) {
                    response.getWriter().write("failure");
                    return;
                }
                String[] airlineData = originalAirline.getFirst().split(",");
                /* airlineData格式：[aid, fid, date, position, remain] */

                // 拆分日期为年、月、日
                String[] dateParts = airlineData[2].split("-"); // date格式：yyyy-MM-dd
                String dateYear = dateParts[0];
                String dateMonth = dateParts[1];
                String dateDay = dateParts[2];

                // 构造更新参数（顺序：aid, fid, dateYear, dateMonth, dateDay, position, remain）
                List<String> updateParams = new ArrayList<>();
                updateParams.add(aid); // aid（WHERE条件）
                updateParams.add(airlineData[1]); // fid
                updateParams.add(dateYear);
                updateParams.add(dateMonth);
                updateParams.add(dateDay);
                updateParams.add(field.equals("position") ? newValue : airlineData[3]); // position
                updateParams.add(field.equals("remain") ? newValue : airlineData[4]);   // remain

                input.addAll(updateParams); // input格式：["modifyAirline", aid, fid, ..., remain]
            }
            case "getFlightsWithoutAirline": {
                // 查询所有航班
                DB_Flight dbFlight = new DB_Flight();
                List<String> allFlights = dbFlight.find(new ArrayList<>());
                
                // 查询所有有席别的航班ID
                DB_Airline dbAirline = new DB_Airline();
                List<String> airlineList = dbAirline.find(new ArrayList<>(List.of("remain>0")));  // 获取有剩余票数的席别
                Set<String> hasAirlineFids = airlineList.stream()
                    .map(airline -> airline.split(",")[1])  // 席别数据格式：[aid,fid,date,position,remain]
                    .collect(Collectors.toSet());
                
                // 过滤出无席别的航班
                List<String> flightsWithoutAirline = allFlights.stream()
                    .filter(flight -> {
                        String fid = flight.split(",")[0];  // 航班数据格式：[fid,starttime,endtime,takeoffstation,arrivalstation,boardingtime]
                        return !hasAirlineFids.contains(fid);
                    })
                    .toList();
                
                // 转换为JSON格式返回（类似GetFlightsServlet的响应结构）
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                StringBuilder json = new StringBuilder();
                json.append("{\"flights\": [");
                for (int i = 0; i < flightsWithoutAirline.size(); i++) {
                    String[] flightData = flightsWithoutAirline.get(i).split(",");
                    json.append("{")
                        .append("\"fid\": \"").append(flightData[0]).append("\",")
                        .append("\"starttime\": \"").append(flightData[1]).append("\",")
                        .append("\"endtime\": \"").append(flightData[2]).append("\",")
                        .append("\"takeoffstation\": \"").append(flightData[3]).append("\",")
                        .append("\"arrivalstation\": \"").append(flightData[4]).append("\",")
                        .append("\"boardingtime\": \"").append(flightData[5]).append("\"")
                        .append("}");
                    if (i < flightsWithoutAirline.size() - 1) json.append(",");
                }
                json.append("], \"totalPages\": 1}");  // 简化分页逻辑，实际可根据需求添加
                out.print(json.toString());
                out.flush();
                return;  // 结束方法，不再执行后续逻辑;
            }
        }

        System.out.println("最终传入input: " + input);
        boolean result = admin.Adjust_flight(input);
        response.getWriter().print(result ? "success" : "fail");
        // response.sendRedirect("adjustFlights.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}